{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 👀 Multilayer perceptron (MLP)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook, we'll walk through the steps required to train your own multilayer perceptron on the CIFAR dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from tensorflow.keras import layers, models, optimizers, utils, datasets\n",
    "from notebooks.utils import display"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 0. Parameters <a name=\"parameters\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "NUM_CLASSES = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Prepare the Data <a name=\"prepare\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_train = x_train.astype(\"float32\") / 255.0\n",
    "x_test = x_test.astype(\"float32\") / 255.0\n",
    "\n",
    "y_train = utils.to_categorical(y_train, NUM_CLASSES)\n",
    "y_test = utils.to_categorical(y_test, NUM_CLASSES)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "display(x_train[:10])\n",
    "print(y_train[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Build the model <a name=\"build\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_layer = layers.Input((32, 32, 3))\n",
    "\n",
    "x = layers.Flatten()(input_layer)\n",
    "x = layers.Dense(200, activation=\"relu\")(x)\n",
    "x = layers.Dense(150, activation=\"relu\")(x)\n",
    "\n",
    "output_layer = layers.Dense(NUM_CLASSES, activation=\"softmax\")(x)\n",
    "\n",
    "model = models.Model(input_layer, output_layer)\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 3. Train the model <a name=\"train\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "opt = optimizers.Adam(learning_rate=0.0005)\n",
    "model.compile(\n",
    "    loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.fit(x_train, y_train, batch_size=32, epochs=10, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 4. Evaluation <a name=\"evaluate\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.evaluate(x_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CLASSES = np.array(\n",
    "    [\n",
    "        \"airplane\",\n",
    "        \"automobile\",\n",
    "        \"bird\",\n",
    "        \"cat\",\n",
    "        \"deer\",\n",
    "        \"dog\",\n",
    "        \"frog\",\n",
    "        \"horse\",\n",
    "        \"ship\",\n",
    "        \"truck\",\n",
    "    ]\n",
    ")\n",
    "\n",
    "preds = model.predict(x_test)\n",
    "preds_single = CLASSES[np.argmax(preds, axis=-1)]\n",
    "actual_single = CLASSES[np.argmax(y_test, axis=-1)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "n_to_show = 10\n",
    "indices = np.random.choice(range(len(x_test)), n_to_show)\n",
    "\n",
    "fig = plt.figure(figsize=(15, 3))\n",
    "fig.subplots_adjust(hspace=0.4, wspace=0.4)\n",
    "\n",
    "for i, idx in enumerate(indices):\n",
    "    img = x_test[idx]\n",
    "    ax = fig.add_subplot(1, n_to_show, i + 1)\n",
    "    ax.axis(\"off\")\n",
    "    ax.text(\n",
    "        0.5,\n",
    "        -0.35,\n",
    "        \"pred = \" + str(preds_single[idx]),\n",
    "        fontsize=10,\n",
    "        ha=\"center\",\n",
    "        transform=ax.transAxes,\n",
    "    )\n",
    "    ax.text(\n",
    "        0.5,\n",
    "        -0.7,\n",
    "        \"act = \" + str(actual_single[idx]),\n",
    "        fontsize=10,\n",
    "        ha=\"center\",\n",
    "        transform=ax.transAxes,\n",
    "    )\n",
    "    ax.imshow(img)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "vscode": {
   "interpreter": {
    "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
